import 'package:dio/dio.dart';
import 'package:get/get.dart';
import 'package:mokeng/utils/utils.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class TransItemController extends GetxController {
  TransItemController({this.value});

  final dynamic value;

  final RxMap<int, dynamic> headerData = <int, dynamic>{}.obs; //存放各楼层数据

  final productList = [].obs; //商品列表

  final sortList = [
    const DropdownItemOption(value: '0', label: '综合排序'),
    const DropdownItemOption(value: '1', label: '近期热度'),
    const DropdownItemOption(value: '3', label: '价格由高到低'),
    const DropdownItemOption(value: '4', label: '价格由低到高'),
  ];

  final selectedSort = Rx<DropdownItemOption?>(null);

  /// UI 组件
  final RefreshController refreshController = RefreshController(
    initialRefresh: false,
  );

  /// 成员变量
  int curPage = 1;
  int pageSize = 20;
  int total = 20;

  /// 事件
  void onRefresh() {
    fetchNewsList(isRefresh: true).then((_) {
      refreshController.refreshCompleted(resetFooterState: true);
    }).catchError((e) {
      refreshController.refreshFailed();
    });
  }

  void onLoading() {
    if (productList.length < total) {
      fetchNewsList().then((_) {
        refreshController.loadComplete();
      }).catchError((e) {
        Get.log('获取数据失败：$e');
        refreshController.loadFailed();
      });
    } else {
      refreshController.loadNoData();
    }
  }

  // 拉取数据
  Future<void> fetchNewsList({bool isRefresh = false}) async {
    var result = await HttpUtil().get(
      value['name'] == "推荐" ? '/pdRelation/getRecommendList' : '/prototype/v2/getList',
      data: {
        "tabId": value['id'],
        "pageNumber": curPage,
        "pageSize": pageSize,
        "sort": selectedSort.value?.value ?? '0',
        "adminPermission": "mokeng666",
      },
      options: Options(headers: {
        "os": "0",
      }),
    );
    if (result['statusCode'] != "200") {
      toast(result['message']);
      return;
    }

    if (isRefresh == true) {
      curPage = 1;
      // total = result.counts!;
      productList.clear();
    } else {
      curPage++;
    }

    productList
        .addAll(result['result'].where((element) => value['name'] == "推荐" ? element['type'] == 0 : true).toList());
  }

  //拉取Bannenr数据
  Future<void> fetchBannerList(int styleType) async {
    var result = await HttpUtil().get('/banner/getList', data: {
      "type": styleType == 14 ? 4 : styleType,
      "adminPermission": "mokeng666",
    });
    if (result['statusCode'] != "200") {
      toast(result['message']);
      return;
    }
    headerData.putIfAbsent(styleType, () => result['result']);
  }

  /// 生命周期
  @override
  void onInit() {
    super.onInit();
  }

  @override
  void onReady() {
    super.onReady();
    fetchNewsList(isRefresh: true);
    for (var element in value['floorList']) {
      var styleType = element['styleType'];
      if (styleType == 1) {
        fetchBannerList(styleType);
      } else if (styleType == 19) {
        headerData.putIfAbsent(styleType, () => "这是一个楼层");
      }
    }
  }

  ///dispose 释放内存
  @override
  void dispose() {
    super.dispose();
    // dispose 释放对象
    refreshController.dispose();
  }
}

class DropdownItemOption {
  const DropdownItemOption({
    required this.value,
    required this.label,
  });

  final String value;
  final String label;
}
